
import {QueryTask} from '../services/receiveTask'
import {Actions} from 'react-native-router-flux'
import { Submit } from '../services/taskReceive'
import { Toast } from 'antd-mobile'

function showToast(){
  Toast.fail('请至少选择 1 位监督员！', 1.5)
}

function genList(arg){
  let tmp = arg.filter(val => {
    return val.selected === true
  })
  if( tmp.length === 0 ) return []
  let obj = {}
  tmp.map((val, index)=> {
     obj[`userIds[${index}]`] = val.id
  })
  return obj
}

export default {

  namespace: 'taskReceive',

  state: {
    userList: [
      // {id: '1', name: '张某某', selected: false},
    ],
    taskIdUnique: '',
  },

  subscriptions: {
  },

  effects: {
    *query({payload}, {put, call, select}){
      const { json, error } = yield call(QueryTask, {taskId: payload.taskId})
      if(json.code === '0'){
        // console.log('Error: ' + json.message)
      }else{
        yield put({type: 'getTaskId', payload: payload.taskId})
        yield put({type: 'querySuccess', payload: json.data})
        Actions.push('ReceiveTask', { ...payload })
      }
    },
    *submit({payload}, {put, call, select}){

      const { userList } = yield select(state => state.taskReceive)
      const {projectId}=yield select(state => state.projectsList);
      const userIds = genList(userList)

      if( userIds.length === 0 ){
        showToast()
      }else{
        const { json, error } = yield call(Submit, {taskId: payload.taskId, ...userIds})
        if(json.code === '0'){
          // console.log('Submit Error: ' + json.message)
        }else{
          yield put({type: 'tasksList/queryTasks'});
          yield put({type:'taskCenter/getTableListNoReceive'})
          yield put({type:'indexPage/getTableListNoReceive'})
          Actions.pop();
        }
      }
    },
    *getTaskId({payload},{call,select,put}){
      const { taskSameId } = yield select (state => state.rectifyBill)
      if(payload.type === 'RectifyBill'){
        if(taskSameId !== payload.id){
          yield put({type:'rectifyBill/getClean'})
          yield put({type:'rectifyBill/setSameId',payload:payload.id})
          yield put({type:'rectifyBill/queryTaskDetail',payload:payload.id})
        }
      }
      yield put({type:'getTaskIdSuccess',payload:payload.id})
    }
  },

  reducers: {
    select(state, {payload}){
      let list = state.userList
      list[payload].selected = !list[payload].selected
      return { ...state, userList: [].concat(list) }
    },
    querySuccess(state, {payload}){
      let list = payload.map(val => {
        let tmp = {id: val.userId, name: val.userName, selected: true}
        return tmp
      })
      return { ...state, userList: list }
    },
    getTaskIdSuccess(state, {payload}){
      return { ...state, taskIdUnique: payload }
    }
  },

}